import {useCallback, useContext} from "react";
import {history} from "@@/core/history";
import {DEFAULT_LOGIN_PATH as LOGIN_PATH} from "@kf-web-library/utils/es/constants";
import querystring from "query-string";
import {useAccess} from "@@/exports";
import {HxConfigContext} from "@/layouts/HxConfigContext";
import {Hash} from "history";


const useAuthedCheck = () => {
  const access = useAccess();
  const {authedRedirect} = useContext(HxConfigContext);
  const authedCheck = useCallback((fn: () => void, redirectHash?: Hash) => {
    if (!access.isLogined) {
      history.push({
          pathname: LOGIN_PATH,
          search: authedRedirect ? querystring.stringify({redirect: authedRedirect}) : "",
          hash: redirectHash,
        }
      );
    } else {
      fn();
    }
  }, []);
  return authedCheck;
};

export default useAuthedCheck;
